// 用户相关的状态管理
import { createSlice } from "@reduxjs/toolkit";
import { request, setToken as setTokenU, getToken as getTokenU } from "../../utils/index";
import { loginAPI } from '../../apis/user'
const userStore = createSlice({
    name:'user',
    // 数据状态
    initialState:{
        token: localStorage.getItem('token_key') || ''
        // token: getTokenU() || ''
    },
    // 同步修改方法
    reducers:{
        setToken(state, action){
            state.token = action.payload
            // redux是基于浏览器内存的存储方式，刷新时状态恢复为初始值，所以要存一份到localStorage里
            // localStorage存一份
            localStorage.setItem('token_key',action.payload)
            // setTokenU(action.payload)
        }
    }
})

// 解构出actionCreater
const { setToken } = userStore.actions
// 获取reducer函数
const userReducer = userStore.reducer

//异步方法 完成登录获取token
const fetchLogin = (loginFrom) => {
    return async (dispatch) => {
        // 1.发送异步请求
        const res = await request.post('/api/xxx',loginFrom)
        // const res = await loginAPI(loginFrom)
        // 2.提交同步action进行token的存入
        dispatch(setTokenU(res.data.token))
    }
}
export { fetchLogin, setToken }
export default userReducer